package com.example.maastock.ontime;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.maastock.entity.MessageDetail;
import com.example.maastock.mapper.MessageDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Slf4j
@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private MessageDetailMapper messageDetailMapper;


    private final String emailServerName = "1332838052@qq.com";

    public void sendEmail(String to, String subject, String text, String stockNumber) {
        if (checkMessageLegitimacy(stockNumber, to)) {
            return;
        }
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setFrom(emailServerName);
        message.setSubject(subject);
        message.setText(text);
        try {
            mailSender.send(message);
        } catch (Exception e) {
            log.info("send to message to error" + e.getMessage());
        }
        MessageDetail messageDetail = spellMessageDetail(message, stockNumber);
        insertIntoDB(messageDetail);
    }


    public MessageDetail spellMessageDetail(SimpleMailMessage message, String stockNumber) {

        MessageDetail messageDetail = new MessageDetail();
        messageDetail.setBusinessDate(LocalDate.now());
        messageDetail.setMessageDetail(message.getText());
        String[] to = message.getTo();

        messageDetail.setMessageTo(String.join(",",to));
        messageDetail.setStockNumber(stockNumber);
        messageDetail.setCreateTime(LocalDateTime.now());
        return messageDetail;

    }


    /**
     * 入库操作message
     */
    public void insertIntoDB(MessageDetail messageDetail) {
        messageDetailMapper.insert(messageDetail);
    }


    /**
     * 同一个股票，一个钟只发一次短信
     */
    public Boolean checkMessageLegitimacy(String stockNumber, String emailAddress) {
        QueryWrapper<MessageDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(MessageDetail::getMessageTo, emailAddress)
                .eq(MessageDetail::getStockNumber, stockNumber)
                .eq(MessageDetail::getBusinessDate, LocalDate.now());
        List<MessageDetail> messageDetails = messageDetailMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(messageDetails)) {
            return false;
        }
        int size = messageDetails.size();
        MessageDetail messageDetail = messageDetails.get(size - 1);
        LocalDateTime createTimeInDataBase = messageDetail.getCreateTime();
        long diffInMinutes = ChronoUnit.MINUTES.between(createTimeInDataBase, LocalDateTime.now()); // 计算时间差（以分钟为单位）
        return diffInMinutes <= 60;

    }


}
